package com.sdp.th.netty.decode;

import java.util.List;

import org.springframework.util.StringUtils;

import com.sdp.th.netty.utils.NettyUtils;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class StringMessageDecoder extends ByteToMessageDecoder {

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		try {
			if (in.isReadable()) {
				byte[] bytes = new byte[in.readableBytes()];
	            in.readBytes(bytes);         
	            
	            //测试用这个
//	            String messageString = new String(bytes, "UTF-8");
	            
	            //实际上线用这个
	            String messageString = NettyUtils.bytesToHex(bytes);
	            
	            log.info("解码器获取到的报文：{},长度：{}",messageString,messageString.length());
				if(StringUtils.isEmpty(messageString) || !messageString.startsWith(NettyUtils.MESSAGE_START)) {
					log.error("报文不合法：{}",messageString);
					return;
				}
				
				if(messageString.length() < NettyUtils.MESSAGE_MIN_LENGTH || messageString.length()>NettyUtils.MESSAGE_MAX_LENGTH) {
					log.error("报文长度不合法：{}",messageString);
					return;
				}
				
				log.info("报文长度合法，进入业务处理");
	            out.add(messageString);
	            bytes = null;
			}
		} catch (Exception e) {
			log.error(NettyUtils.stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace()));
		}
		
	}

}
